<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="11" style="height: 85vh; overflow-y:scroll; display: flex;">
            <a-row :gutter="48">
              <!-- <div>234444</div> -->
              <!-- <a-col :span="10">
                <a-form-model-item label="进度模板" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateNodeId">
                  <select-process-template-input v-model="model.templateNodeId" disabled placeholder="请选择进度模板" :multi="false" @input="getTemplateList" />
                </a-form-model-item>
              </a-col>
              <a-col :span="10">
                <a-form-model-item label="允许添加子节点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isAddChildNode">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.isAddChildNode"
                    disabled
                    dictCode="yes_no"
                    placeholder="请选择允许添加子节点"
                  />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="20" class="taskNodeFormClass">
                <a-steps direction="vertical" v-model="current" @change="onChange" :style="stepStyle">
                  <a-step
                    v-for="(item,index) in nodeList"
                    :key="index"
                    :description="getProgressText(item)"
                    :status="item.choose==1? 'process': (item.bpmStatus== '3' ? 'finish' :'wait')">
                    <span slot="title">
                      <span style="" v-if="!item.isChild || item.isChild == '0'"><a-tag color="pink"> 主节点 </a-tag></span>
                      <span style="" v-else><a-tag color="orange"> 子节点 </a-tag></span>
                      {{ item.nodeName }}
                    </span>
                  </a-step>
                </a-steps>
              </a-col>
              <a-col :span="4">
                <a
                  style="font-size: 14px; display: block; height: 65px; text-align:center; padding-top:7px; width: 58px;"
                  v-for="(value, ind) in planList"
                  :key="ind"
                  @click="handlePlan(value)"
                >{{ value.planTitle }}</a>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="13">
            <a-card :bordered="false">
              <!-- <a-form-model-item label="预计总工时" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expectTotalHours">
                <a-input :disabled=formDisabled   v-model="model.expectTotalHours" placeholder="请输入预计总工时" style="width: 100%" />
              </a-form-model-item> -->
              <!-- <a-form-model-item label="实际效能分" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="realEfficacy">
                <a-input :disabled="formDisabled" v-model="model.realEfficacy" placeholder="请输入实际效能分" style="width: 100%" />
              </a-form-model-item> -->
              <div slot="title">
                <!-- 判断当前节点是否可以添加子节点,“isAddChildNode == 0”则隐藏 -->
                <!-- 判断当前节点是否已经填报完成，完成则不禁用, -->
                <a-button
                  style="display: inline-block; margin-right: 8px; float: right"
                  v-if="nodeChildDisabled"
                  type="primary"
                  icon="plus"
                  @click="handleChildAdd"
                >添加子节点</a-button>
                <a-button
                  style="display: inline-block; margin-right: 8px; float: right"
                  v-if="nodeChildDeleteShow"
                  type="primary"
                  icon="delete"
                  @click="handleChildDelete"
                >删除子节点</a-button>
                <a-button
                  style="display: inline-block; margin-right: 8px; float: right"
                  v-if="ProcessBtnShow"
                  type="primary"
                  @click="handleTrack(model)"
                >审批进度</a-button>
                <p style="overflow: visible; white-space: normal; text-overflow:clip">{{ formTitle }}</p>
              </div>
              <!-- <a-form-model-item label="消耗工时(天)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="consumedHours">
                <a-input-number
                  :disabled="formDisabled"
                  v-model="model.consumedHours"
                  placeholder="请输入消耗工时"
                  style="width: 100%"
                  :max="99999999"
                  :min="0"
                  :precision="1" />
              </a-form-model-item> -->
              <!-- <a-form-model-item label="完成状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskCompleteStatus">
                <j-dict-select-tag :disabled="formDisabled" type="radio" v-model="model.taskCompleteStatus" dictCode="finish_status" @input="statusChange" placeholder="请选择完成状态" />
              </a-form-model-item> -->
              <a-form-model-item label="完成时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="completeTime">
                <j-date
                  :disabled="formDisabled"
                  placeholder="请选择完成时间"
                  v-model="model.completeTime"
                  :disabledDate="disabledDate"
                  :disabledTime="disabledDateTime"
                  :show-time="true"
                  date-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%" />
              </a-form-model-item>
              <a-form-model-item label="完成情况" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="completeDesc">
                <a-textarea :max-length="1000" :disabled="formDisabled" v-model="model.completeDesc" rows="4" placeholder="请输入完成情况" />
              </a-form-model-item>
              <!-- <a-form-model-item label="下一节点预计完成时间" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="model.taskCompleteStatus === '2'" prop="nextNodeEstimatedCompletionTime">
                <j-date
                  :disabled="formDisabled"
                  placeholder="请选择完成时间"
                  v-model="model.nextNodeEstimatedCompletionTime"
                  :show-time="true"
                  date-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%" />
              </a-form-model-item> -->
              <a-form-model-item label="证明材料" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="nodeFile">
                <!-- 当流程结束或者未开始的可以重新录入数据，重新判断数据怎么走 -->
                <!-- 判断是否为完全完成的状态 -->
                <template v-if="record && record.taskStatus == 'finish'">
                  <j-upload v-if="isHasPerm('progress:update:file')" v-model="model.nodeFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.nodeFile)">证明材料</a-button>
                </template>
                <template v-else-if="!disabled && model.bpmStatus != '2'">
                  <!-- 当流程已完成的时候需判断是否需要上传文件 -->
                  <template v-if="model.bpmStatus == '3'">
                    <j-upload v-if="isHasPerm('progress:update:file')" v-model="model.nodeFile"></j-upload>
                    <a-button v-else icon="download" @click="viewFile(model.nodeFile)">证明材料</a-button>
                  </template>
                  <j-upload v-else v-model="model.nodeFile"></j-upload>
                </template>
                <!-- 处理中的节点和点击查看不可以上传文件 -->
                <a-button v-else icon="download" @click="viewFile(model.nodeFile)">证明材料</a-button>
              </a-form-model-item>
              <div style="width: 100%;display:flex;align-items: center;justify-content: center;" v-if="submitBtnShow">
                <a-button
                  @click="submitForm('submit')"
                  type="primary"
                  style=" margin-bottom: 0; margin-right: 20px"
                >提交流程</a-button>
                <a-button
                  @click="submitForm('draft')"
                  type="primary"
                  style=" margin-bottom: 0;"
                >暂存</a-button>
              </div>
              <div style="width: 100%;display:flex;align-items: center;justify-content: center;" v-if="finishFileSubmitBtnShow">
                <a-button
                  @click="submitForm('finish')"
                  type="primary"
                  style=" margin-bottom: 0;"
                >保存</a-button>
              </div>

            </a-card>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <view-file-modal ref="viewFileModal"></view-file-modal>
    <a-modal
      :maskClosable="false"
      title="应收关联"
      width="75vw"
      centered
      :bodyStyle="{
        padding: '0 24px',
      }"
      :visible="visible"
      @cancel="handleCancel"
    >
      <a-card
        :bordered="false"
        :bodyStyle="{
          padding: '10px 24px',
        }"
        style="width: 100%; height: 80vh; overflow-y: auto;"
      >
        <a-table
          ref="table"
          rowKey="id"
          bordered
          :scroll="{x:true}"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="false"
          class="j-table-force-nowrap"
          wrapClassName="ant-modal-cust-warp"
        ></a-table>
      </a-card>
      <template slot="footer">
        <a-button @click.stop="()=>{visible=false}">关闭</a-button>
      </template>
    </a-modal>

    <!-- 点击添加子节点弹窗 -->
    <erp-progress-task-node-child-node-modal ref="childNodeModal" @ok="childNodeFormOk"></erp-progress-task-node-child-node-modal>
    <process-config-modal ref="processConfig" @ok="handleSuccess" @close="handleClose"></process-config-modal>
    <bpm-process-track-modal ref="bpmProcessTrackModal"></bpm-process-track-modal>
  </a-spin>
</template>

<script>

  import { httpAction, getAction, postAction, deleteAction } from '@/api/manage'
  import { viewFile } from '@/utils/util'
  import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
  import ViewFileModal from '@/views/scy/components/ViewFileModal'
  import ErpProgressTaskNodeChildNodeModal from './reference/ErpProgressTaskNodeChildNodeModal.vue'
  import { mapGetters } from 'vuex';
  import moment from 'moment';
  import SelectProcessTemplateInput from '@/views/scy/components/SelectProcessTemplateInput' // 进度模板

  import ProcessConfigModal from '@/views/scy/components/ProcessConfigModal'
  import BpmProcessTrackModal from '@/views/modules/bpmbiz/common/BpmProcessTrackModal.vue'; // 审批流程弹窗
  export default {
    name: 'ErpProgressTaskNodeForm',
    mixins: [viewFile, DisabledAuthFilterMixin],
    components: {
      ViewFileModal,
      ErpProgressTaskNodeChildNodeModal,
      ProcessConfigModal,
      SelectProcessTemplateInput,
      BpmProcessTrackModal
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        complateDisable: false,
        stepStyle: {
          marginBottom: '60px',
          boxShadow: '0px -1px 0 0 #e8e8e8 inset'
        },
        visible: false,
        dataSource: [],
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: '应收款项节点',
            align: 'center',
            dataIndex: 'nodeName',
            ellipsis: true

          },
          {
            title: '款项金额',
            align: 'center',
            dataIndex: 'taskPaymentMoney',
            ellipsis: true

          }
        ],
        formTitle: '',
        planList: [],
        current: 0,
        currentInit: 0,
        nodeList: [],
        nodeListInit: [], // 初始列表
        model: {},
        record: {},
        dataForm: {},
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          // 消耗工时
          consumedHours: [
            { required: true, message: '请输入消耗工时!' },
            { pattern: /^(([0-9][0-9]*)|([0]\.\d{0,1}|[1-9][0-9]*\.\d{0,1}))$/, message: '消耗工时请输入数字,小数点后最多一位!' }
          ],
          taskCompleteStatus: [
            { required: true, message: '请选择完成状态!' }
          ],
          completeTime: [
            { required: true, message: '请选择完成时间!' }
          ],
          nextNodeEstimatedCompletionTime: [
            { required: true, message: '请选择下一节点预计完成时间!' }
          ],
          completeDesc: [
            { required: true, message: '请输入完成情况!' }
          ],
          nodeFile: [
            { required: true, message: '请上传证明材料!' }
          ],
          expectTotalHours: [
            { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,1}|[1-9][0-9]*\.\d{0,1}))$/, message: '预计总工时请输入数字,小数点后最多一位!' }
          ]
        },
        url: {
          add: '/api/erp/progress/erpProgressTaskNode/add',
          addAll: '/api/erp/progress/erpProgressTaskNode/finishAll', // 全部完成
          edit: '/api/erp/progress/erpProgressTaskNode/edit',
          queryById: '/api/erp/progress/erpProgressTaskNode/queryById',
          queryNodeListById: '/api/erp/progress/erpProgressTaskNode/queryTaskNodeInfoById'
        },
        flowCode: 'onl_erp_progress_task_node',
        formUrl: '/erp/progress/modules/ErpProgressTaskNodeProcessForm',
        beanName: 'erpProgressTaskNodeServiceImpl',
        processId: '1827972723015086082',
        formUrlMobile: '/pages/synergy/erpProgressTaskNodeForm'
      }
    },
    computed: {
      formDisabled() {
        // 判断当节点已完成表单的字段是禁用
        if (this.disabled || this.model.bpmStatus != '1') {
          return true
        } else {
          return false
        }
        // if (this.disabled) {
        //   return this.disabled
        // } else {
        //   return this.complateDisable
        // }
      },
      nodeChildDisabled () {
        // 循环nodeList判断当前主节点的第二个主节点是否已经流程完成，如果流程完成则不可点击添加子节点按钮
        const arrList = this.nodeList.filter((item, index) => {
          if (index > this.current) {
            return item
          }
        })
        // 在抹除arrList中所有的子节点，在去判断第一个主节点有没有流程完成，完成则禁用按钮
        const arrList1 = arrList.filter((item, index) => {
          if (item.isChild == '0') {
            return item
          }
        })
        // 当前节点是否可以添加子节点
        if (this.model.isAddChildNode && this.model.isAddChildNode == '1' && !this.disabled) {
          // 判断当前的主节点已经流程填报完成和下一个主节点没有流程完成，则当前主节点可以显示子节点
          if (this.model.bpmStatus == '3' && (arrList1.length && (!arrList1[0].bpmStatus || arrList1[0].bpmStatus == '1'))) {
            return true
          } else {
            return false
          }
        } else {
          // 不可以直接不显示
          return false
        }
      },
      // 判断删除子节点按钮的回显
      nodeChildDeleteShow () {
        // 当该节点是子节点，且处于待提交的状态则回显删除子节点按钮
        if ((this.model.isChild && this.model.isChild == '1') && this.model.bpmStatus == '1' && !this.disabled) {
          return true
        } else {
          return false
        }
      },
      // 判断审批进度按钮回显
      ProcessBtnShow () {
        // 判断当该节点在流程中或者流程完成时回显该按钮
        if (this.model.bpmStatus != '1') {
          return true
        } else {
          return false
        }
      },
      // 判断保存审批按钮回显
      submitBtnShow () {
        if (!this.disabled && this.model.bpmStatus == '1') {
          return true
        } else {
          return false
        }
      },
      // 判断流程已完成时附件是否可以上传
      finishFileSubmitBtnShow () {
        // 当是全部完成状态时
        console.log('this.record', this.record)
        if (this.record && this.record.taskStatus == 'finish') {
          if (this.isHasPerm('progress:update:file')) {
            return true
          } else {
            return false
          }
        } else if (!this.disabled && this.model.bpmStatus == '3' && this.isHasPerm('progress:update:file')) {
          return true
        } else {
          return false
        }
      }
    },
    watch: {
      'model.isValidateRequired': {
        handler (val) {
          if (val && val == 1) {
            this.$set(this.validatorRules, 'nodeFile', [{ required: true, message: '请上传证明材料!' }])
          } else {
            this.$set(this.validatorRules, 'nodeFile', [{ required: false, message: '请上传证明材料!' }])
          }
        },
        immediate: true,
        deep: true
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      ...mapGetters(['userInfo']),
      disabledDate(date) {
        return date && date > moment().endOf('day');
      },
      getTemplateList(val){
        console.log('val',val)
      },
      range(start, end) {
        const result = [];
        for (let i = start; i < end; i++) {
          result.push(i);
        }
        return result;
      },
      disabledDateTime(time) {
        // 判断选择的日期是否小于当前日期，如果否，则禁用当前日期及以后的时间
        if (moment(time).isSame(moment(), 'day')) {
          return {
            disabledHours: () => this.range(Number(moment().format('HH')) + 1, 24),
            disabledMinutes: () => this.range(Number(moment().format('mm')) + 1, 60),
            disabledSeconds: () => this.range(Number(moment().format('ss')) + 1, 60)
          }
        } else {
          return false
        }
      },
      getProgressText(data) {
        if (data.nodeProgress) {
          return data.nodeProgress + '%' + (data.completeTime && data.taskCompleteStatus == '2' ? (' ' + data.completeTime) : '')
        }
      },
      // 点击添加子节点
      handleChildAdd () {
        this.$refs.childNodeModal.add(this.model)
        this.$refs.childNodeModal.title = '创建子节点'
        this.$refs.childNodeModal.disableSubmit = false
      },
      // 删除子节点
      handleChildDelete () {
        var that = this
        this.$confirm({
          title: '确定删除子节点?',
          content: '删除子节点后，所填的信息也将删除',
          okType: 'danger',
          onOk() {
            deleteAction('/api/erp/progress/erpProgressTaskNode/delete', { id: that.nodeList[that.current].id }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.queryNodeList(true)
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        });
      },
      // 审批进度
      handleTrack(record) {
        let flowCode = this.flowCode;
        var params = { flowCode: flowCode, dataId: record.id };// 查询条件
        this.$refs.bpmProcessTrackModal.handleTrack(params);
        this.$refs.bpmProcessTrackModal.title = '审批跟踪记录';
      },
      // 子节点添加完成
      childNodeFormOk (val) {
        let params = {
          handlerId: this.userInfo().empId, // 当前登录人Id
          parentNodeId: this.model.id, // 父节点id
          progressTaskId: this.model.progressTaskId, // 	任务进度Id
          taskId: this.model.taskId, // 任务Id
          nodeName: val.nodeName, // 节点名称
          nodeProgress: val.nodeProgress, // 节点名称
          isValidateRequired: val.isValidateRequired, // 证明材料是否必填
          isChild: 1 // 必传
        }
        postAction('/api/erp/progress/erpProgressTaskNode/add', params).then(res => {
          if (res.success) {
            this.$message.success(res.message);
            this.queryNodeList(true)
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      // 切换完成状态
      statusChange(current) {
        // 当完成状态为未完成时，清空下一节点预计完成时间字段
        if (current === '1') {
          this.$set(this.model, 'nextNodeEstimatedCompletionTime', null)
        }
      },
      // 切换步骤条
      onChange(current) {
        console.log('current--', current)
        if (!this.disabled) {
          // 判断当前节点是否填报
          // if (!this.nodeListInit[current].taskCompleteStatus) {
          //   // 当已经填报了
          //   var finishCurrent = this.nodeListInit.findIndex(item => {
          //     return item.taskCompleteStatus
          //   })
          //   if (current > finishCurrent) {
          //     if (current != 0) {
          //       if (!this.nodeListInit[current - 1].taskCompleteStatus || this.nodeListInit[current - 1].taskCompleteStatus == 1) {
          //         this.current = this.currentInit
          //         return false
          //       }
          //     }
          //   }
          // }
          this.currentInit = current
        }

        this.$refs.form.clearValidate();
        this.nodeList[current].choose = '1'
        for (var i = 0; i < this.nodeList.length; i++) {
          if (i != current) {
            this.nodeList[i].choose = '0'
          }
        }
        if (this.nodeList[current].complateDisable == '2') {
          this.complateDisable = true;
        } else {
          this.complateDisable = false;
        }
        this.formTitle = this.nodeList[current].nodeName
        this.model = this.nodeList[current]
        this.current = current;
        console.log('this.nodeList[current]--', this.nodeList[current])
          
        
      },
      add () {
        this.nodeList = []
        this.current = 0
        this.edit(this.modelDefault);
      },
      async edit (record) {
        this.nodeList = []
        this.formTitle = ''
        this.current = 0
        this.currentInit = 0
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        this.record = Object.assign({}, record);
        this.dataForm = Object.assign({}, record);
        this.queryNodeList()
      },
      queryByNodeIds () {
        let params = {
          taskId: this.record.projectTaskId
        }
        getAction('/api/erp/omc/project/erpOmcProjectTaskProgressNode/queryByTaskIds', params).then((res) => {
          if (res.success) {
            // 对比节点列表，循环节点列表
            var arrList = [] // 款项列表数据
            this.nodeList.map((value, index) => {
              res.result.map((item, ind) => {
                if (value.id == item.taskNodeId) {
                  // 判断款项是否绑定的是同一个任务进度，如果是则往planObj数组塞一个对象

                  arrList.push({
                    planArr: [{ ...item }],
                    nodeObj: { ...value },
                    planTitle: '应收关联'
                  })
                } else {
                  arrList.push({
                    planArr: [{ ...item }],
                    nodeObj: { ...value },
                    planTitle: ''
                  })
                }
              })
            })
            // 数组对象按照nodeObj中的id值是否重复去重
            for (let i = 0; i < arrList.length; i++) {
              for (let j = i + 1; j < arrList.length; j++) {
                if (arrList[i].nodeObj.id == arrList[j].nodeObj.id) {
                  // 判断planTitle是否有值
                  if (arrList[i].planTitle && arrList[j].planTitle) {
                    // 当前后都有值，则说明款项绑定了相同的任务进度，则合并
                    arrList[i].planArr = [...arrList[i].planArr, ...arrList[j].planArr]
                    // 删除重复的
                    arrList.splice(j, 1);
                  } else if (arrList[i].planTitle) {
                    // 前面有值删后面
                    arrList.splice(j, 1);
                  } else if (arrList[j].planTitle) {
                    // 后面有值删前面
                    arrList.splice(i, 1);
                  } else {
                    // 无所谓
                    arrList.splice(j, 1);
                  }
                  j--;
                };
              };
            };
            this.planList = arrList
          } else {
            this.planList = []
          }
        })
      },
      queryNodeList(arg) {
        // 查看节点列表
        if (this.model.id) {
          var params = {
            // 第一次点填报进入的时候没有 progressTaskId 所以取 record 中的 this.model.id
            // 接口调用后 id 会变成 progressTaskId
            id: this.model.progressTaskId || this.model.id,
            column: 'sortOrder'
          }
          getAction(this.url.queryNodeListById, params).then((res) => {
            if (res.success) {
              this.nodeList = res.result
              this.nodeListInit = JSON.parse(JSON.stringify(res.result))
              if (this.nodeList && this.nodeList.length) {
                var currentIndex = 0
                // var finishCurrent = this.nodeList.findIndex(item => {
                //   return !!item.taskCompleteStatus
                // })
                // 查找nodeList中的taskCompleteStatus有没有等于2，代表已完成的有则返回下标
                const nodeListIndex = this.findLastIndex(this.nodeList, 'taskCompleteStatus', '2')
                if (nodeListIndex == -1) {
                  // 查找nodeList中的taskCompleteStatus有没有等于1代表未完成的有则返回下标
                  const nodeListIndex1 = this.findLastIndex(this.nodeList, 'taskCompleteStatus', '1')
                  if (nodeListIndex1 == -1) {
                    // 都没有直接为0，代表没有点击保存
                    currentIndex = 0
                  } else {
                    currentIndex = nodeListIndex1
                  }
                } else {
                  currentIndex = nodeListIndex + 1
                }
                this.nodeList.map((value, index) => {
                  if (value.taskCompleteStatus == '2') {
                    value.complateDisable = true;
                  } else {
                    value.complateDisable = false;
                  }
                })
                if (currentIndex >= this.nodeList.length) {
                  currentIndex = this.nodeList.length - 1
                }
                if (arg) {
                  currentIndex = this.current
                }
                this.model = this.nodeList[currentIndex]
                this.nodeList[currentIndex].choose = '1'
                this.current = currentIndex
                this.currentInit = currentIndex
                this.formTitle = this.nodeList[currentIndex].nodeName
                if (this.nodeList[currentIndex].taskCompleteStatus && this.nodeList[currentIndex].taskCompleteStatus == '2') {
                  this.complateDisable = true;
                } else {
                  this.complateDisable = false;
                }
              }
              this.queryByNodeIds() // 获取任务进度对应的款项值
            }
          })
        }
      },
      findLastIndex (array, value, key) {
        /**
        * 倒着查找下标
        *   @property {Array}           array             循环的数组
        *   @property {String}          value             指定的值
        *   @property {String}          key               指定的key
        */
        let arr = JSON.parse(JSON.stringify(array))
        const index = arr.reverse().findIndex(item => item[value] == key)
        // 如果找到了，需要将下标转换回正确的方向
        let correctIndex = index === -1 ? index : arr.length - 1 - index;
        return correctIndex
      },
      // 点击查看款项列表
      handlePlan (record) {
        // return
        if (record.planTitle) {
          this.dataSource = (record.planArr && record.planArr.length) ? record.planArr : []
          this.visible = true
        }
      },
      handleCancel () {
        this.visible = false
      },
      // 判断该任务进度是否绑定了款项
      // validateTaskPayment () {
      //   let params = {
      //     taskId: this.record.progressTaskId
      //   }
      //   getAction('/api/erp/omc/contractmanager/erpOmcContractPlanTaskFinal/validateTaskPayment', params).then((res) => {
      //       if (res.success) {

      //       }
      //     })
      // },

      validateForm() {
        var that = this
        return this.$refs.form.validate().then(async () => {
          var isJudge = -1
          let params = {
            taskId: that.record.projectTaskId
          }
          await getAction('/api/erp/omc/contractmanager/erpOmcContractPlanTaskFinal/validateTaskPayment', params).then((res) => {
            if (res.success) {
              // return res.success
            } else {
              isJudge = 1
              that.$message.warning(res.message);
            }
          })
          if (isJudge != -1) {
            return Promise.reject('该任务进度未关联款项，请通过变更任务委托关联')
          }
          return Promise.resolve()
        })
      },

      async submitForm (type) {
        const that = this;
        var params = await this.model
        params.id = await this.nodeList[this.current].id
        params.isFill = '1'
        console.log('this.model', this.model)
        params.taskCompleteStatus = this.model.taskCompleteStatus || '1' // 完成状态默认未完成，需要走流程完成
        params.handlerId = await this.userInfo().empId
        params.applyTime = await moment().format('YYYY-MM-DD HH:mm:ss'); // 申请时间
        params.createTime = await moment().format('YYYY-MM-DD HH:mm:ss'); // 创建时间
        params.handlerDeptId = await this.userInfo().deptId; // 当前登录人部门
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          // 校验数据是否需要走变更任务委托
          await this.validateForm()
          // 校验数据是否可以被提交流程
          const resp = await postAction('/api/erp/progress/erpProgressTaskNode/submitVerify', params)
          if (!resp.success) {
            this.$message.warning(resp.message)
            return Promise.reject(resp.message)
          }
            that.submit(type)
          } else if (type == 'finish') {
            // 校验数据是否填写
            await this.validateForm()
            this.submit(type)
          } else {
            console.log('传参数，保存：draft，提交：submit')
          }
        },
      submit(type) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = this.url.edit;
        let method = 'put';
        this.model.id = this.nodeList[this.current].id
        this.model.isFill = '1'
        this.model.taskCompleteStatus = this.model.taskCompleteStatus || '1' // 完成状态默认未完成，需要走流程完成
        this.model.handler = this.userInfo().empId
        this.model.applyTime = moment().format('YYYY-MM-DD HH:mm:ss'); // 申请时间
        this.model.handlerDeptId = this.userInfo().deptId; // 当前登录人部门
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (type && this.model && type == 'submit') {
              this.beginProcess(this.model)
            }
          } else {
            that.$message.warning(res.message);
            // that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$message.warning(error.message);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },
      beginProcess(record) {
        this.$refs.processConfig.visible = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(record, this.processId, this.beanName)
      },
      handleSuccess() {
        this.$emit('close');
      },
      handleClose() {
        this.$emit('close');
      },
      async validateFormAll() {
        var that = this
        var isJudge = -1
          let params = {
            taskId: that.record.projectTaskId
          }
          await getAction('/api/erp/omc/contractmanager/erpOmcContractPlanTaskFinal/validateTaskPayment', params).then((res) => {
              if (res.success) {
                // return res.success
              } else {
                isJudge = 1
                that.$message.warning(res.message);
              }
            })
          if (isJudge != -1) {
            let text = '该任务进度未关联款项，请通过变更任务委托关联'
            return Promise.reject(text)
          }
          return Promise.resolve()
      },
      async submitFormAll () {
        let that = this
        await this.validateFormAll()
        that.confirmLoading = true;
            let httpurl = this.url.addAll;
            let method = 'post';
            var taskObject = {
              taskId: this.nodeList[this.current].taskId,
              id: this.nodeList[this.current].id,
              progressTaskId: this.dataForm.id
            }
            httpAction(httpurl, taskObject, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('close');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
      }
    }
  }
</script>
<style>
.ant-steps ant-steps-vertical{
  margin-bottom: 60px;
}

.taskNodeFormClass .ant-steps-item-title {
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
  width: 19vw !important;
}
</style>
